<script lang="ts" setup>
import { ref, reactive, toRefs, watch } from "vue" // vue
import { FormInstance, ElMessageBox, ElMessage } from "element-plus" // elment
import { Search, Refresh } from "@element-plus/icons-vue" // 按钮图标
import Editor from "@/components/RichText/index.vue" // 引入富文本
import { usePagination } from "@/hooks/usePagination" // 分页器
import { formatDateTime } from "@/utils" // 时间戳转换
import { getDataApi, createDataApi, delDataApi, createDataHFApi, delDataHFApi } from "@/api/repository/askRepository" // 接口
import { useUserStore } from "@/store/modules/user" // 获取用户信息
const userStore = useUserStore() // 获取用户信息
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination() // 分页器

// 表单
const data = reactive<any>({
  formData: {},
  form: {
    content: "<p><br></p>"
  },
  searchData: {
    pageNum: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    content: undefined
  }, // 表单验证
  rules: {
    content: [
      {
        required: true,
        message: "请输入问题",
        trigger: "blur"
      }
    ]
  }
})
const { searchData, formData, rules, form } = toRefs(data)

// #region 查
const tableData = ref<any>([])
function tablelist() {
  getDataApi({ ...searchData.value, pageNum: paginationData.currentPage, pageSize: paginationData.pageSize })
    .then((res: any) => {
      tableData.value = res.data.data
      paginationData.total = res.data.count
      console.log(tableData.value)
    })
    .catch(() => {
      tableData.value = []
    })
}
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
// 搜索
function handleSearch() {
  console.log(1)
  searchData.value.pageNum = 1
  tablelist()
}
// 重置
function resetSearch() {
  console.log(2)
  searchFormRef.value?.resetFields()
  handleSearch()
}
// #endregion

// #region 页面展开与收起
const expand = ref()
function goUpDown(e: any) {
  if (expand.value == e) {
    expand.value = undefined
  } else {
    expand.value = e
  }
}
// 控制展开样式
function expandclass(index: any) {
  return expand.value == index ? "expandBox2" : "expandBox"
}
// #endregion

// #region 添加和修改框
const dialogVisible = ref(false)
const formRef = ref<FormInstance | null>(null)
const ids = ref(undefined) // 判断修改还是增加

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`您确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delDataApi({ id: row }).then(() => {
      ElMessage.success("删除成功")
      tablelist()
    })
    console.log(row, 3)
  })
}

// 清空form框
const clearValidate = () => {
  formRef.value?.resetFields()
}

// 清空对话框
const resetForm = () => {
  ids.value = undefined
  clearValidate()
  formData.value = {}
}

// 确定按钮
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (ids.value === undefined) {
        createDataApi(formData.value).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          tablelist()
        })
      }
    } else {
      return false
    }
  })
}
// #endregion

// #region 回复功能
console.log(userStore.usernameID, "用户信息id")
// 要根据用户信息来判断删除功能
const getMsgHF = (val: any) => {
  if (val) {
    form.value.content = val
  }
}
// 提交回复
const onSubmit = (e: any) => {
  if (form.value.content == "<p><br></p>") {
    ElMessage.error("不能回复空内容")
  } else {
    console.log(e, "问题id")
    createDataHFApi({ ...form.value, questionId: e }).then(() => {
      ElMessage.success("回复成功")
      tablelist()
      //  回复成功后将回复框清空
      form.value.content = "<p><br></p>"
    })
  }
}
// 删除回复
const handleDeleteHF = (row: any) => {
  ElMessageBox.confirm(`您确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    console.log(row, 4)
    delDataHFApi({ id: row }).then(() => {
      ElMessage.success("删除成功")
      tablelist()
    })
  })
}
// #endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], tablelist, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card>
      <el-row justify="center" align="middle">
        <el-col :span="14">
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="content" label="问题搜索">
              <el-input v-model.trim="searchData.content" clearable placeholder="请输入" style="width: 500px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
              <el-button @click="dialogVisible = true">新增问题</el-button>
            </el-form-item>
          </el-form></el-col
        >
      </el-row>
    </el-card>

    <el-card style="margin-top: 20px; padding: 50px">
      <div v-for="(item, index) in tableData" :key="index">
        <div class="footbox">
          <div>
            <span>创建人：{{ item.createUserName }}</span>
            <span class="spans">提问时间：{{ formatDateTime(item.createTime) }}</span>
          </div>
          <div style="display: flex">
            <!--  1.删除发布的问题先和自己id比对如果相同就显示删除按钮 -->
            <el-button
              v-if="userStore.usernameID == item.createUserId"
              @click="handleDelete(item.id)"
              type="primary"
              link
            >
              删除
            </el-button>
            <div style="margin-left: 50px" @click="goUpDown(index)">
              <el-button v-if="expand !== index" type="primary" link> 回复 </el-button>
              <el-button v-else type="primary" link> 收起 </el-button>
            </div>
          </div>
        </div>
        <p style="margin-bottom: 20px">问题：{{ item.content }}</p>

        <div :class="expandclass(index)">
          <!-- for循环回复数组 -->
          <div v-for="(i, d) in item.questionReplies" :key="d" class="divclassHF">
            <div>{{ i.createUserName }} 回答：</div>
            <div class="classHF">
              <div style="margin-left: 90px" v-html="i.content" />
              <!-- 拿到评论的id与自己id做对比 如果相同那么显示删除按钮可以删除 -->
              <el-button
                v-if="userStore.usernameID == i.createUserId"
                @click="handleDeleteHF(i.id)"
                type="primary"
                link
              >
                删除
              </el-button>
            </div>
          </div>
          <!-- 回复框 -->
          <div>
            <el-form :model="form" label-width="auto">
              <el-form-item prop="content">
                <Editor :value="form.content" @updateValue="getMsgHF" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit(item.id)">回复</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <el-divider />
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="paginationData.total"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" @closed="resetForm" width="60%">
      <el-form ref="formRef" :model="formData" label-width="100px" label-position="left" :rules="rules">
        <el-form-item prop="content" label="问题">
          <el-input v-model="formData.content" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.expandBox {
  max-height: 0px;
  min-height: 0px;
  overflow: hidden;
  transition: max-height ease-in-out 0.2s;
}
.expandBox2 {
  min-height: 80px;
  overflow: hidden;
  transition: max-height ease-in-out 0.2s;
}
.footbox {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
.spans {
  margin-left: 20px;
}
.classHF {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}
.divclassHF {
  background-color: #f2f3f5;
  padding: 20px;
  margin-bottom: 20px;
}
</style>
